<?php


namespace app\common\lib\live;


use app\chat\LiveMessage;
use app\common\cachemodel\live\LiveAnchorInfo;
use app\common\cachemodel\live\LiveAnswerAstroRecord;
use app\common\cachemodel\live\LiveAnswerDiceRecord;
use app\common\cachemodel\live\LiveAnswerTarotRecord;
use app\common\lib\Push;
use app\common\lib\SensorsData;
use app\common\model\MessageCenter;
use think\Log;
use think\queue\Job;

class LiveAnswerJob
{
    private $config = [
        1 => [
            'type' => 'astro',
            'need_auth' => 1,
        ],
        2 => [
            'type' => 'dice',
            'need_auth' => 1,
        ],
        3 => [
            'type' => 'tarot',
            'need_auth' => 1,
        ],
    ];

    /**
     * 超时响应 队列
     * @param Job $job
     * @param $jobData
     * @return void
     * @throws \Exception
     */
    public function answerClientTimeOutTask(Job $job, $jobData)
    {   // 付费解答响应超时 检测
        switch ($jobData['type'])
        {
            case 1: // 看盘
                $liveAnswerModel = new LiveAnswerAstroRecord();
                $orderType = 19;
                $answerName = '看盘';
                break;
            case 2: // 骰子
                $liveAnswerModel = new LiveAnswerDiceRecord();
                $orderType = 20;
                $answerName = '骰子';
                break;
            case 3: // 塔罗
                $liveAnswerModel = new LiveAnswerTarotRecord();
                $orderType = 21;
                $answerName = '塔罗';
                break;
            default:
                $job->delete();
                return;
        }

        $nowAnswerInfo = $liveAnswerModel->getNowAnswerDataByCache($jobData['live_record_id']);

        if ($nowAnswerInfo && $nowAnswerInfo['answer_sign'] === $jobData['answer_sign'] && (int)$nowAnswerInfo['status'] === 3)
        {   // 状态  1=>待支付 2=>等待解答｜排队中  3=>待响应 4=>未响应 5=>解答中 6=>解答完成 7=>未响应3次后取消 8=>用户主动取消 9=>主播取消 10=>订单关闭取消
            // 等一会 删除当前解答中的缓存信息
            $liveAnswerModel->delNowAnswerDataByCache($jobData['live_record_id']);

            $answerInfo = $liveAnswerModel->getInfoById($nowAnswerInfo['id']);

            $answerList = $liveAnswerModel->getRequestAnswerUserList((int)$answerInfo['live_id'], (int)$jobData['live_record_id'], 2);
            if ($answerInfo['wait_num'] >= 2)
            {   // 稍等一会 次数达上线
                // 更新订单并退款
                $res = $liveAnswerModel->refundAnswerOrder(['id' => $answerInfo['id'], 'order_num' => $answerInfo['order_num'], 'status' => (int)$answerInfo['status'], 'uid' => $answerInfo['uid'], 'wait_num' => $answerInfo['wait_num'] + 1,], (int)$jobData['live_record_id'], 4, '');
                if ($res === false)
                {
                    exit;
                }
                // 删除 排队信息
                $liveAnswerModel->delRequestAnswerUserList((int)$answerInfo['live_id'], (int)$jobData['live_record_id'], 2, (int)$answerInfo['uid']);
                // 加入取消订单列表
                $liveAnswerModel->addResAnswerUserList((int)$jobData['live_record_id'], 2, [$answerInfo['id'] => $answerInfo['id']]);
                $answerDelayStatus = 3;
                unset($answerList[$answerInfo['uid']]);

                // 消息中心添加信息
                $messageData = [
                    'status' => 0,
                    'is_read' => 0,
                    'range' => $answerInfo['uid'],
                    'type' => 2,
                    'reid' => 0,
                    'cid' => 4,
                    'title' => '解答响应超时订单取消',
                    'content' => '非常抱歉，您的' . $answerName . '解答订单：' . $answerInfo['order_num'] . '因您响应超时被取消，您支付的资金将原路返还，请注意查收',// 消息中心跳转地址
                    'link' => "order_details?order_id={$answerInfo['order_num']}&order_type={$orderType}",
                    'target' => 'local',
                    'create_time' => time()
                ];
                (new MessageCenter())->pushMessage($answerInfo['uid'], $messageData);
                if (!LiveMessage::getUidIsOnline($nowAnswerInfo['live_id'], $nowAnswerInfo['uid']))
                {   // 直播间不在线   则发送推送消息
                    // 发送推送
                    (new Push())->pushUserMsg($answerInfo['uid'], '非常抱歉，您的' . $answerName . '解答订单：' . $answerInfo['order_num'] . '因您响应超时被取消，您支付的资金将原路返还，请注意查收', ['action' => 'extend', 'target' => 'local', 'link' => "order_details?order_id={$answerInfo['order_num']}&order_type={$orderType}"]);
                }

            } else
            {
                $answerDelayStatus = 2;
                // 更新解答状态
                $liveAnswerModel->updateAnswerRequest([
                    'id' => (int)$nowAnswerInfo['id'],
                    'status' => 4,
                    'wait_num' => $answerInfo['wait_num'] + 1,
                ]);
            }
            // ws 消息
            // 当前用户发送通知
            LiveMessage::sendMsg(LiveMessage::who(LiveMessage::WHO_TYPE_UID, $nowAnswerInfo['live_id'], $nowAnswerInfo['uid'])
                , LiveMessage::MSG_TYPE_POP_ANSWER_REFRESH, [
                    'target' => 'local',
                    'link' => "live_{$this->config[$jobData['type']]['type']}?id={$nowAnswerInfo['id']}&live_record_id={$jobData['live_record_id']}&need_auth={$this->config[$jobData['type']]['need_auth']}",
                    'type' => (int)$jobData['type'],
                    'force_open' => 1
                ]);
            // 主播发送
            // 向管理员 发送消息
            LiveMessage::sendMsg(LiveMessage::who(LiveMessage::WHO_TYPE_LIVER, $nowAnswerInfo['live_id'], $nowAnswerInfo['live_id'])
                , LiveMessage::MSG_TYPE_POP_LIVE_ANSWER_RESPONSE_STATUS, [
                    'type' => (int)$jobData['type'],
                    'status' => $answerDelayStatus,
                    'id' => $nowAnswerInfo['id']
                ]);
            // 图标显隐消息
            // if (!$answerList)
            // {
            LiveMessage::sendMsg(LiveMessage::who(LiveMessage::WHO_TYPE_LIVER, $nowAnswerInfo['live_id'], $nowAnswerInfo['live_id'])
                , LiveMessage::MSG_TYPE_POP_LIVE_ANSWER_ICON, [
                    'icon' => "/live/answer/{$this->config[$jobData['type']]['type']}_icon.png",
                    'hint' => '',
                    'target' => 'local',
                    'link' => 'live_request_list?type=' . $jobData['type'],
                    'type' => (int)$jobData['type'],
                    'status' => 0,
                ]);
            // }
            // 排队用户
            foreach ($answerList as $uidItem => $idItem)
            {
                $idItem = (int)$idItem;
                LiveMessage::sendMsg(LiveMessage::who(LiveMessage::WHO_TYPE_UID, $nowAnswerInfo['live_id'], $uidItem)
                    , LiveMessage::MSG_TYPE_POP_ANSWER_REFRESH, [
                        'target' => 'local',
                        'link' => "live_{$this->config[$jobData['type']]['type']}?id={$idItem}&live_record_id={$jobData['live_record_id']}&need_auth={$this->config[$jobData['type']]['need_auth']}",
                        'type' => (int)$jobData['type'],
                        'force_open' => 0
                    ]);
            }
            $anchoInfo = (new LiveAnchorInfo())->getInfoById($answerInfo['live_id'], ['name']);
            //  直播取消订单成功 LiveQuestionCancle 打点
            SensorsData::track($answerInfo['uid'], true, 'LiveQuestionCancle', [
                'hoster_name' => $anchoInfo['name'],    // 主播名称
                'live_id' => $answerInfo['live_id'],    // 直播间ID
                'live_record_id' => $jobData['live_record_id'],  // 直播记录ID
                'price' => $answerInfo['price'] * 1,   //  价格
                'cancle_reason' => '自动取消',
                'question_type' => $answerName,   // 解答类型
                'question' => $answerInfo['question'] ?? '',    // 问题的具体内容
                'description' => $answerInfo['question_des'] ?? '无', // 问题的描述
            ]);
        }
        // 删除队列
        $job->delete();
    }

    /**
     * 下单超时 队列
     * @param Job $job
     * @param $jobData
     * @throws \Exception
     */
    public function answerDownOrderTimeOutTask(Job $job, $jobData)
    {
        switch ($jobData['type'])
        {
            case 1: // 看盘
                $liveAnswerModel = new LiveAnswerAstroRecord();
                break;
            case 2: // 骰子
                $liveAnswerModel = new LiveAnswerDiceRecord();
                break;
            case 3: // 塔罗
                $liveAnswerModel = new LiveAnswerTarotRecord();
                break;
            default:
                $job->delete();
                return;
        }

        $answerInfo = $liveAnswerModel->getUserRequestAnswerPrepareInfo((int)$jobData['live_id'], (int)$jobData['live_record_id'], (int)$jobData['uid']);

        if ($answerInfo && $answerInfo['sign'] === $jobData['sign'] && (int)$answerInfo['status'] === 0)
        {
            // 删除提交信息
            $liveAnswerModel->delUserRequestAnswerPrepareInfo((int)$jobData['live_id'], (int)$jobData['live_record_id'], (int)$jobData['uid']);
            // 删除占位信息
            $liveAnswerModel->delAnswerPrepareUser($answerInfo['live_id'], $answerInfo['uid']);
            // 写日志
            Log::write('直播间下单超时：' . json_encode($jobData, JSON_UNESCAPED_UNICODE), 'log');
        }

        $job->delete();
    }
}
